from datetime import datetime

from fastapi import APIRouter, Depends, Request, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession

from config.get_db import get_db
from module_monitor.entity.vo.monitor_vo import MonitorModel
from module_rag.entity.vo.rag_vo import RagPageQueryModel
from module_rag.service.rag_service import RagService
from module_monitor.service.monitor_service import MonitorService
from utils.log_util import logger
from utils.minio_util import upload_file_to_minio, get_file_type
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

apiController = APIRouter(prefix='/api')


@apiController.get(
    '/rag/list', response_model=PageResponseModel
)
async def get_rag_list(
    request: Request,
    rag_page_query: RagPageQueryModel = Depends(RagPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    rag_page_query_result = await RagService.get_rag_list_services(query_db, rag_page_query, is_page=False)
    logger.info('获取成功')

    return ResponseUtil.success(rows=rag_page_query_result)

@apiController.post('/detect/upload')
async def upload_file(
        device_id: str = Form(...),
        monitor_type: str = Form(...),
        file: UploadFile = File(...),
        query_db: AsyncSession = Depends(get_db)
):
    add_monitor = MonitorModel()
    add_monitor.device_id = device_id
    add_monitor.monitor_type = monitor_type
    add_monitor.file_type = get_file_type(file.filename)
    add_monitor.file_name = file.filename
    # 上传文件到 MinIO
    download_url = upload_file_to_minio(file)['download_url']
    add_monitor.file_url = download_url
    # 入库
    add_monitor.create_time = datetime.now()
    add_monitor.update_time = datetime.now()
    add_monitor_result = await MonitorService.add_monitor_services(query_db, add_monitor)

    logger.info(add_monitor_result.message)
    return ResponseUtil.success(msg=add_monitor_result.message)
